class TicketTemplate < ActiveRecord::Base
  has_many :note_types, :dependent => :destroy, :order => "priority"
  has_many :tickets, :dependent => :destroy
  has_many :report_templates, :dependent => :destroy
  validates_presence_of :name
  validates_uniqueness_of :name
  validates_length_of :name, :within => 1..100
  after_update :save_note_types
  validates_associated :note_types, :message => "are invalid"

  def duplicate
    ticket_template = TicketTemplate.new
    for column in TicketTemplate.content_columns
      ticket_template.send(column.name+'=', self.send(column.name))
    end
    ticket_template.note_types = []
    self.note_types.each {|nt|
      new_nt = NoteType.new()
      for column in NoteType.content_columns
        new_nt.send(column.name+'=', nt.send(column.name))
      end
      ticket_template.note_types << new_nt
      }
    ticket_template.name += " copy"
    if !(TicketTemplate.find(:first, :conditions => ["name = (?)", ticket_template.name]))
       ticket_template.save!
    else
      i=1
      while TicketTemplate.find(:first, :conditions => ["name = (?)", ticket_template.name + "(#{i.to_s})"])
        i += 1
      end
      ticket_template.name += "(#{i.to_s})"
      ticket_template.save!
    end
  end
  
  def note_type_attr=(nt_attributes)
    nt_attributes.each do |attributes|
      if attributes[:id].blank?
        note_types.build(attributes)
      else
        note_type = note_types.detect { |t| t.id == attributes[:id].to_i }
        note_type.attributes = attributes
      end
    end
  end
  
  def save_note_types
    note_types.each do |t|
      if t.should_destroy?
        t.destroy
      else
        t.save(false)
      end
    end
  end
  
  def note_types_col(i)
    self.note_types.select{|nt| nt.col_number == i}
  end

  def validate_on_create
    note_types.each_with_index{|note_type,i|
      if note_type.priority != i
        errors.add(:note_types, "Internal error with priorities")
      end
    }
  end
  
end
